import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:xinxuan/common/button_util.dart';
import 'package:xinxuan/common/culling_goods_arr.dart';
import 'package:xinxuan/common/network_image_util.dart';
import 'package:xinxuan/common/scroll_configuration_common.dart';
import 'package:xinxuan/common/swiper_util.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/controllers/cooperation_controller/cooperation_page_controller.dart';
import 'package:xinxuan/controllers/home_controller/home_page_controller.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:x_common_utils/utils/inkWell_util.dart';
import 'package:get/get.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/utils/refresh_util.dart';
import 'package:xinxuan/vo/activities_list_vo.dart';
import 'package:xinxuan/vo/categoires_list_vo.dart';

class HomePage extends StatelessWidget {

  final HomePageController controller = Get.put(HomePageController());
  final CommonPageController commonPageController = Get.find();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: pageBgColor,
      appBar: AppBar(
        backgroundColor: bgWhiteColor,
        elevation: 0,
        titleSpacing: 0,
        title: Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Image.asset(
                'assets/icons/icon_text_logo.png',
                width: 72.w,
                height: 22.h,
                fit: BoxFit.cover,
              ),
              Row(
                children: [
                  GetBuilder<CommonPageController>(
                    builder: (controller) {
                      return InkWellUtil.shakeProofInkWell(Image.asset(
                        'assets/icons/icon_notice.png',
                        width: 20.w,
                        height: 20.w,
                      ), () {
                        if (controller.isRevirew.value) {
                          controller.tabIndex.value = 1;
                        } else {
                          controller.tabIndex.value = 2;
                        }
                      });
                    },
                  ),
                  Obx(() => commonPageController.isSign.value ? Row(
                    children: [
                      SizedBox(width: 16.w),
                      InkWellUtil.shakeProofInkWell(Image.asset(
                        'assets/icons/icon_sign.png',
                        width: 20.w,
                        height: 20.w,
                      ), () {
                        commonPageController.userSignDialog();
                      })
                    ],
                  ) : Container())
                ],
              )
            ],
          ),
        ),
      ),
      body: GetBuilder<HomePageController>(
        builder: (controller) {
          return Stack(
            children: [
              Column(
                children: [
                  SizedBox(height: 44.h),
                  Expanded(child: ScrollConfigurationCommon(child: 
                    RefreshUtil.easyRefresh(
                      onRefresh: () async {
                        controller.initPageDate();
                      },
                      onLoad: () async {
                        controller.onloadFeaturesList();
                      },
                      slivers: [
                        SliverList(
                          delegate: SliverChildListDelegate([
                            Container(
                              margin: EdgeInsets.only(top: 12.h),
                              child: SwiperUtil(
                                images: controller.bannerArr, 
                                width: 350.w, 
                                height: 122.h, 
                                borderRadius: 8.w, 
                                padding: 12.w
                              ),
                            ),
                            _kingGangBody(controller),
                            _newsBody(controller),
                            _blindBoxitem(controller),
                            _mouTaiItem(controller),
                            Container(
                              height: 49.h,
                              child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemCount: 3,
                                itemBuilder: (context, index) {
                                  return InkWellUtil.shakeProofInkWell(Container(
                                    width: 94.w,
                                    alignment: Alignment.center,
                                    child: Obx(() => Text(
                                      '${controller.goodThingTypeArr[index]['title']}',
                                      style: TextStyle(
                                        color: controller.goodThingTypeIndex.value == index ? mainTextColor : textBlackColor,
                                        fontSize: controller.goodThingTypeIndex.value == index ? 18.sp : 16.sp
                                      ),
                                    )),
                                  ), () {
                                    controller.goodThingTypeIndex.value = index;
                                    controller.getFeaturesList(loading: true);
                                  }, 
                                  hoverColor: Colors.transparent,
                                  splashColor: Colors.transparent,
                                  highlightColor: Colors.transparent);
                                }
                              ),
                            )
                          ]),
                        ),
                        CullingGoodsArr(goodsArr: controller.featuresListVo.value.data!)
                        // SliverToBoxAdapter(
                        //   child: Container(
                        //     margin: EdgeInsets.only(top: 12.h),
                        //     child: Column(
                        //       children: [
                        //         Container(
                        //           child: SwiperUtil(
                        //             images: controller.bannerArr, 
                        //             width: 350.w, 
                        //             height: 122.h, 
                        //             borderRadius: 8.w, 
                        //             padding: 12.w
                        //           ),
                        //         ),
                        //         _kingGangBody(controller),
                        //         _newsBody(controller),
                        //         _blindBoxitem(controller),
                        //         _mouTaiItem(controller)
                        //       ],
                        //     ),
                        //   ),
                        // ),
                        // SliverToBoxAdapter(
                        //   child: _goodThings(controller),
                        // ),
                      ]
                    )
                  ))
                ],
              ),
              Positioned(
                // top: 0,
                // left: 0,
                child: _searchBar(),
              )
            ],
          );
        },
      ),
    );
  }
  /// 搜索栏目
  Widget _searchBar() {
    return Container(
      height: 44.h,
      padding: EdgeInsets.only(left: 16.w, right: 16.w),
      decoration: BoxDecoration(
        color: bgWhiteColor,
        boxShadow: [
          BoxShadow(
            color: boxShadow_006,
            offset: Offset(0, 3.h),
            blurRadius: 6.h
          )
        ]
      ),
      alignment: Alignment.center,
      child: InkWellUtil.shakeProofInkWell(Container(
        padding: EdgeInsets.only(left: 14.w, right: 2.w, top: 2.h, bottom: 2.h),
        height: 36.h,
        decoration: BoxDecoration(
          border: Border.all(
            color: bgMainColor,
            width: 1.w
          ),
          borderRadius: BorderRadius.circular(36.h)
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(child: Row(
              children: [
                Image.asset(
                  'assets/icons/icon_search.png',
                  width: 18.w,
                  height: 18.w,
                ),
                SizedBox(width: 10.w),
                Text(
                  '请您输入商品',
                  style: TextStyle(
                    color: textSubtitleColor,
                    fontSize: 14.sp
                  ),
                )
              ],
            )),
            Container(
              width: 60.w,
              child: ButtonUtil(
                text: '搜索', 
                fontSize: 14.sp, 
                borderRadius: 30.w, 
                height: 30.h, 
                onTop: () {
                  Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.SEARCH_PAGE}');
                }
              ),
            )
          ],
        ),
      ), () {
        Get.toNamed('${AppRouters.COMMON_PAGE}${AppRouters.SEARCH_PAGE}');
      }),
    );
  }

  /// 金刚区
  Widget _kingGangBody(HomePageController controller) {
    double height = 86.h;
    if (controller.categoiresArr.length >= 2) {
      if (controller.categoiresArr.length >= 1 && controller.categoiresArr[0].length <= 4 ) {
        height = 178.h;
      }
    }
    return Container(
      height: height,
      margin: EdgeInsets.symmetric(vertical: 12.h),
      child: controller.categoiresArr.length <= 0 ? Container() : Swiper(
        itemBuilder: (context, index) {
          List<CategoiresItem> arr = controller.categoiresArr[index];
          return Container(
            padding: EdgeInsets.symmetric(horizontal: 23.w),
            // padding: EdgeInsets.only(left: 23.w),
            child: Wrap(
              spacing: 43.w,
              runSpacing: 20.h,
              children: arr.map((item) {
                return _kingGangItem(
                  item.id!,
                  item.image ?? '', 
                  item.title ?? ''
                );
              }).toList(),
            ),
          );
        }, 
        itemCount: controller.categoiresArr.length,
        loop: false,
        pagination: SwiperCustomPagination(
          builder: (BuildContext context, SwiperPluginConfig config) {
            return Container(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: controller.categoiresArr.asMap().keys.map((index) {
                  if (index == config.activeIndex) {
                    return Container(
                      width: 18.w,
                      height: 5.w,
                      margin: EdgeInsets.symmetric(horizontal: 3.w),
                      decoration: BoxDecoration(
                        color: mainTextColor,
                        borderRadius: BorderRadius.circular(5.w)
                      ),
                    );
                  } else {
                    return Container(
                      width: 13.w,
                      height: 5.w,
                      margin: EdgeInsets.symmetric(horizontal: 3.w),
                      decoration: BoxDecoration(
                        color: bgSubColor,
                        borderRadius: BorderRadius.circular(5.w)
                      ),
                    );
                  }
                }).toList()
              ),
            );
          }
        ),
      ),
    );
  }

  /// 金刚区Item
  Widget _kingGangItem(int id, String url, String title) {
    return InkWellUtil.shakeProofInkWell(Container(
      child: Column(
        children: [
          NetworkImageUtil(
            url: url, 
            width: 48.w, 
            height: 48.w,
          ),
          SizedBox(height: 6.h),
          Text(
            title,
            style: TextStyle(
              color: textBlackColor,
              fontSize: 12.sp
            ),
          )
        ],
      ),
    ), () {
      Get.toNamed(
        '${AppRouters.COMMON_PAGE}${AppRouters.SEARCH_PAGE}${AppRouters.SEARCH_RECORD_PAGE}',
        arguments: {
          'category_id': id,
          'title': title
        }
      );
    });
  }

  /// 公告
  Widget _newsBody(HomePageController controller) {
    return Container(
      child: Container(
        height: 49.h,
        padding: EdgeInsets.symmetric(horizontal: 25.w),
        decoration: BoxDecoration(
          color: bgWhiteColor,
          border: Border.symmetric(
            horizontal: BorderSide(
              width: .5,
              color: lineColor
            )
          )
        ),
        child: Row(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 5),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3.w),
                border: Border.all(
                  width: .5,
                  color: bgMainColor
                )
              ),
              child: Text(
                '通知',
                style: TextStyle(
                  color: mainTextColor,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.bold
                ),
              ),
            ),
            SizedBox(width: 6.w),
            Expanded(child: Container(
              height: 49.h,
              padding: EdgeInsets.only(left: 5.w),
              child: controller.newsArr.length <= 0 ? Container() : Swiper(
                scrollDirection: Axis.vertical,
                autoplay: true,
                itemBuilder: (context, index) {
                  return InkWellUtil.shakeProofInkWell(Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '${controller.newsArr[index].description}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: textBlackColor,
                        fontSize: 14.sp
                      ),
                    ),
                  ), () { 
                    controller.clickNoticeItem(
                      title: '${controller.newsArr[index].title}', 
                      description: '${controller.newsArr[index].description}'
                    );
                  });
                }, 
                itemCount: controller.newsArr.length
              ),
            ))
          ],
        ),
      ),
    );
  }

  // /// 精选好物
  // Widget _goodThings(HomePageController controller) {
  //   FeaturesListVo featuresListVo = controller.featuresListVo.value;
  //   return Container(
  //     child: Column(
  //       children: [
  //         Container(
  //           height: 56.h,
  //           child: ListView.builder(
  //             scrollDirection: Axis.horizontal,
  //             itemCount: 3,
  //             itemBuilder: (context, index) {
  //               return InkWellUtil.shakeProofInkWell(Container(
  //                 width: 94.w,
  //                 alignment: Alignment.center,
  //                 child: Obx(() => Text(
  //                   '${controller.goodThingTypeArr[index]['title']}',
  //                   style: TextStyle(
  //                     color: controller.goodThingTypeIndex.value == index ? mainTextColor : textBlackColor,
  //                     fontSize: controller.goodThingTypeIndex.value == index ? 18.sp : 16.sp
  //                   ),
  //                 )),
  //               ), () {
  //                 controller.goodThingTypeIndex.value = index;
  //                 controller.getFeaturesList(loading: true);
  //               }, 
  //               hoverColor: Colors.transparent,
  //               splashColor: Colors.transparent,
  //               highlightColor: Colors.transparent);
  //             }
  //           ),
  //         ),
  //         CullingGoodsArr(goodsArr: featuresListVo.data!)
  //       ],
  //     ),
  //   );
  // }

  /// 盲盒模块
  Widget _blindBoxitem(HomePageController controller) {
    return InkWellUtil.shakeProofInkWell(Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      margin: EdgeInsets.only(top: 16.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/blindbox_banner.png',
            width: 343.w,
            height: 92.h,
            fit: BoxFit.cover,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 16.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.vertical(bottom: Radius.circular(5.w)),
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  homeBlindBoxBg,
                  homeBlindBoxBg1
                ]
              )
            ),
            child: Container(
              padding: EdgeInsets.only(left: 8.w, right: 12.w, top: 16.h, bottom: 16.h),
              decoration: BoxDecoration(
                color: bgWhiteColor,
                borderRadius: BorderRadius.circular(5.w)
              ),
              child: Row(
                children: [
                  NetworkImageUtil(
                    url: '${controller.blindboxActivityData.value.image}', 
                    width: 97.w, 
                    height: 97.w,
                    borderRadius: 5.w,
                  ),
                  SizedBox(width: 12.w),
                  Expanded(child: Container(
                    constraints: BoxConstraints(
                      minHeight: 97.w
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '${controller.blindboxActivityData.value.title}',
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: textBlackColor,
                            fontSize: 14.sp
                          ),
                        ),
                        SizedBox(height: 6.h),
                        Text(
                          '${controller.blindboxActivityData.value.sales}人已预约',
                          style: TextStyle(
                            color: textSubtitleColor,
                            fontSize: 12.sp
                          ),
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              padding: EdgeInsets.only(bottom: 3.h),
                              child: Text.rich(
                                TextSpan(
                                  text: '¥',
                                  style: TextStyle(
                                    color: mainTextColor,
                                    fontSize: 14.sp
                                  ),
                                  children: [
                                    TextSpan(
                                      text: '${controller.blindboxActivityData.value.price}',
                                      style: TextStyle(
                                        color: mainTextColor,
                                        fontSize: 18.sp
                                      ),
                                    )
                                  ]
                                )),
                            ),
                            Container(
                              width: 56.w,
                              height: 34.h,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5.w),
                                gradient: LinearGradient(
                                  begin: Alignment.bottomCenter,
                                  end: Alignment.topCenter,
                                  colors: [
                                    bgMainColor,
                                    bgExcessiveColor
                                  ]
                                )
                              ),
                              child: Text(
                                '去预约',
                                style: TextStyle(
                                  color: textWhiteColor,
                                  fontSize: 12.sp
                                ),
                              ),
                            )
                          ],
                        )
                      ],
                    ),
                  ))
                ],
              ),
            ),
          )
        ],
      ),
    ), () {
      if (controller.blindboxActivityData.value.id == 0) {
        return;
      }
      if (commonPageController.isAuthenticated.value) {
        if (commonPageController.userData.value.isInvatition == 0) {
          EasyLoading.showToast('用户必须先添加邀请人');
          commonPageController.tabIndex.value = 1;
          CooperationPageController cooperationPageController = Get.put(CooperationPageController());
          cooperationPageController.joinTeam();
          return;
        }
      }
      Get.toNamed(
        '${AppRouters.COMMON_PAGE}${AppRouters.BLIND_BOX_DETAIL_PAGE}',
        arguments: {
          'id': controller.blindboxActivityData.value.id
        }
      );
    });
  }

  /// 茅台板块
  Widget _mouTaiItem(HomePageController controller) {
    if (controller.activitiesArr.length <= 0) {
      return Container();
    }
    ActivitiesItem activitiesItem = controller.activitiesArr[0];
    return InkWellUtil.shakeProofInkWell(Container(
      margin: EdgeInsets.only(top: 12.h),
      padding: EdgeInsets.only(left: 16.w, right: 16.w),
      child: Container(
        width: 343.w,
        height: 219.h,
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              'assets/images/moutai_bg.png'
            ),
            fit: BoxFit.cover
          ),
        ),
        child: Column(
          children: [
            Container(
              height: 46.h,
              alignment: Alignment.centerLeft,
              child: Text(
                '${activitiesItem.title}',
                style: TextStyle(
                  color: textWhiteColor,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold
                ),
              ),
            ),
            Container(
              width: 319.w,
              height: 161.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5.w),
                color: bgWhiteColor,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Stack(
                    children: [
                      NetworkImageUtil(
                        url: '${activitiesItem.image}', 
                        width: 319.w, 
                        height: 161.h,
                        borderRadius: 5.w,
                      ),
                      Positioned(
                        bottom: 0,
                        child: Container(
                          width: 319.w,
                          padding: EdgeInsets.symmetric(horizontal: 6.w),
                          decoration: BoxDecoration(
                            color: bgWhiteColor_70,
                            borderRadius: BorderRadius.vertical(bottom: Radius.circular(5.w))
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '¥${activitiesItem.products![0].price}+${activitiesItem.products![0].integral}积分',
                                textAlign: TextAlign.justify,
                                style: TextStyle(
                                  color: mainTextColor,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold
                                ),
                              ),
                              Text(
                                '${activitiesItem.products![0].title}',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: textBlackColor,
                                  fontSize: 14.sp
                                ),
                              )
                            ],
                          ),
                        )
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    ), () {
      Get.toNamed(
        '${AppRouters.COMMON_PAGE}${AppRouters.GOOD_DETAIL_PAGE}',
        arguments: {
          'goodId': activitiesItem.products![0].id
        }
      );
    });
  }
}